<template>
  <div>
    <Tabs value="name1">
      <TabPane label="草稿箱" name="name1">
        <div v-for="(item, index) in list" :key="index" class="draftItem">
          <div class="top">
            <div class="top-left">
              <div class="left-info">
                <!-- <img class="header-img" :src="item.face" alt="" /> -->
                <Avatar
                class="header-img"
                @on-error="(val)=>val.target.src = require('@/assets/communityimg/avatar.png')"
                shape="circle"
                :src="item.face"
                icon="ios-person"
                size="28"
              />
                <div class="info">
                  <div class="name">{{ item.nick_name }}
                    <span class="leiCla">{{getAuthenticatioStatus(item)}}</span>
                  </div>
                  <div class="time">{{ item.time }}</div>
                </div>
              </div>
              <div class="del-box">
                <span @click="editData(item)"><Icon type="ios-create-outline" />编辑</span>
                <span style="color: #ff340a" @click="delId(item)"><Icon type="ios-trash" />删除</span>
              </div>
            </div>
          </div>
          <div class="main">
            <div class="text" style="font-size: 14px;color: #0f1011">{{ item.title }}</div>
            <div class="text" style="padding: 10px 0">{{ item.content }}</div>
            <div class="imgs" v-if="item.imgs">
              <img
                class="imgs-item"
                :src="v"
                alt=""
                v-for="(v, i) in item.imgs"
                :key="i"
              />
            </div>
            <div v-if="item.videos">
              <video
                v-for="b in item.videos"
                :src="b"
                height="200px"
                width="100%"
                controls
              ></video>
            </div>
            <!-- <div class="imgs">
              {{item.imgs.length}}
              <img :src="item.imgs[0]" alt="" />
            </div> -->
          </div>
        </div>
      </TabPane>
    </Tabs>
    <Modal
      v-model="editShow"
      :mask-closable="false"
      title="编辑"
      width="800"
      ok-text="发布"
      @on-ok="handleSubmit('formValidate')">
      <div style="height: 280px">
        <Form style="padding-top: 10px" ref="formValidate" :label-width="0" :model="formValidate" :rules="ruleValidate">
          <FormItem label="" prop="titleText">
            <Input v-model="formValidate.titleText" maxlength="20" style="width: 400px" placeholder="请填写标题(必填，最多20字)"></Input>
          </FormItem>
          <FormItem label="" prop="contText">
            <Input v-model="formValidate.contText" type="textarea" maxlength="300" placeholder="请填写正文(必填)"></Input>
          </FormItem>
        </Form>

        <div class="live">
          <div class="live-left">
            <Poptip placement="bottom-start" popper-class="popCla" width="400" word-wrap>
              <Icon type="ios-paper-outline" />图片
              <div class="text type-box" slot="content">
                <div class="sub-box">
                  <div class="demo-upload-list" v-for="(img, index) in uploadList" :key="index">
                    <img :src="img">
                    <div class="demo-upload-list-cover">
                      <!--<Icon type="ios-eye-outline" @click.native="handleView(img)"></Icon>-->
                      <Icon type="ios-trash-outline" @click.native="handleRemove(index)"></Icon>
                    </div>
                  </div>
                  <Upload
                    :show-upload-list="false"
                    :on-success="handleSuccess"
                    :on-format-error="handleSuccessLu"
                    :before-upload="handleBeforeUpload"
                    :format="['jpg','jpeg','png']"
                    :action="action"
                    :headers="accessToken"
                    style="display: inline-block;width:60px;">
                    <div class="hover-pointer icon-upload" style="width: 60px;height: 60px;text-align: center;line-height: 60px">
                      <Icon type="ios-camera" size="20"></Icon>
                    </div>
                  </Upload>
                </div>
              </div>
            </Poptip>
            <Poptip placement="bottom-start" popper-class="popCla" width="400"  style="margin-left: 20px">
              <Icon type="logo-youtube" />视频
              <div class="text type-box" slot="content">
                <div class="sub-box">
                  <div class="demo-upload-list" style="width: 100px" v-for="(img, index) in uploadListVideo" :key="index">
                    <video
                      style="width: 100px"
                      :src="img"
                    >
                    </video>
                    <div class="demo-upload-list-cover">
                      <Icon type="ios-trash-outline" @click.native="handleRemoveVideo(index)"></Icon>
                    </div>
                  </div>
                  <Upload
                    :show-upload-list="false"
                    :on-success="handleSuccessVideo"
                    :on-format-error="handleSuccessVideoLu"
                    :before-upload="handleBeforeUploadVideo"
                    :format="['mp4','avi']"
                    :action="action"
                    :headers="accessToken"
                    style="display: inline-block;width:60px;">
                    <div class="hover-pointer icon-upload" style="width: 100px;height: 100px;text-align: center;">
                      <div style="padding: 5px 0"><span style="font-size: 16px;">上传视频</span> <span style="color: #999999">支持上传MP4格式文件，不超过1GB</span></div>
                      <div style="padding-top: 10px;border: 1px #e8e8e8 solid;width: 60px;height: 60px;color: #999999">
                        <div>上传视频</div>
                        <Icon type="md-add" size="20"></Icon>
                      </div>
                    </div>
                  </Upload>
                </div>
              </div>
            </Poptip>
          </div>
          <div class="live-right">
            <Cascader :data="typeList" v-model="value1" :load-data="loadData" @on-change="casChange">
              <div class="defult">
                <div>
                  {{ defultcircle }}
                </div>
                <Icon type="ios-arrow-down"></Icon>
              </div>
            </Cascader>
            <!--<button class="sub" @click="handleSubmit('formValidate')">发布</button>-->
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
  import {getActiveList,delDraftId,getChosList,getChosStatus,editChosInfo}from "@/api/community"
  import { commonUrl } from '@/plugins/request';
export default {
  data() {
    return {
      delshow: false,
      delindex: -1,
      list: [],
      editShow:false,
      editRow:{},
      value1: ['0'],
      defultcircle: "草稿",
      typeList: [
        {
          value: "0",
          label: "公开的",
          children: [],
        },
        {
          value: "1",
          label: "同步圈子",
          children: [],
          loading: false
        },
        {
          value: "2",
          label: "仅自己可见",
          children: [],
        },
        {
          value: "3",
          label: "草稿",
          children: [],
        },
      ],
      formValidate:{
        titleText:'',
        contText:'',
      },
      ruleValidate: {
        titleText: [
          { required: true, message: '请填写标题(必填，最多20字)', trigger: 'blur' }
        ],
        contText: [
          { required: true, message: '请填写正文(必填)', trigger: 'blur' }
        ],
      },
      action: commonUrl + '/common/common/upload/file', // 上传地址
      accessToken: {}, // 验证token
      uploadList:[],
      uploadListVideo:[],
    };
  },
  mounted(){
    this.accessToken.accessToken = localStorage.getItem("accessToken");
    this.getList()
  },
  methods: {
    getAuthenticatioStatus(item) {
      if (item.auth && item.auth.status === 1) {
        return item.auth.title;
      }
      return "";
    },
    delId(row){
      let params = {
        mid: JSON.parse(localStorage.userInfo).id,
        id:row.id
      }
      delDraftId(params).then((res) =>{
        if(res.code == '1'){
          this.$Message.success("删除成功")
          this.getList()
        }else {
          this.$Message.error(res.msg || '获取数据失败!');
        }
      })
    },
    getList() {
      let params = {
        mid:JSON.parse(localStorage.userInfo).id,
        page:'1',
        pagesize:'1000'
      }
      getActiveList(params).then((res) =>{
        if(res.code == '1'){
          res.data.forEach((a) =>{
            if(a.thumbs) a.imgs = a.thumbs.split(',') || []
            if(a.video_url) a.videos = a.video_url.split(',') || []
            a.time = this.setTime(a.creattime)
          })
          this.list = res.data
        }else {
          this.$Message.error(res.msg || '获取数据失败!');
        }
      })
    },
    setTime(val){
      let str = null
      if(val.length > 10){
        str = new Date(parseInt(val))
      }else {
        str = new Date(parseInt(val) * 1000)
      }
      let year = str.getFullYear()
      let mon = str.getMonth() > 9 ? str.getMonth() : '0' + str.getMonth()
      let day = str.getDay() > 9 ? str.getDay() : '0' + str.getDay()
      let hou = str.getHours() > 9 ? str.getHours() : '0' + str.getHours()
      let min = str.getMinutes() > 9 ? str.getMinutes() : '0' + str.getMinutes()
      let sen = str.getSeconds() > 9 ? str.getSeconds() : '0' + str.getSeconds()
      return year + '-' +  mon + '-' + day + ' ' + hou + ':' + min +  ":" + sen
    },
    editData(row){
      console.log(row,'row');
      this.formValidate.titleText = row.title
      this.formValidate.contText = row.content
      this.value1[0] = row.push_status.toString()
      this.uploadList = row.thumbs ? row.thumbs.split(',') : []
      this.uploadListVideo = row.video_url ? row.video_url.split(',') : []
      this.editRow = row
      this.editShow = true
    },
    casChange(val){
      if(val[0] == '1'){
        let params = {
          id:val[1],
          mid:JSON.parse(localStorage.userInfo).id
        }
        getChosStatus(params).then((res) =>{
          if(res.code !== 1) this.$Message.error(res.msg || '该圈子不能发表!');
        })
      }
      if(val[0]){
        this.defultcircle = this.typeList.filter((a) =>{return a.value == val[0]})[0].label
      }
      if(val[0] && val[1]){
        this.defultcircle = this.typeList.filter((a) =>{return a.value == val[0]})[0].label
          + '·' + this.typeList[1].children.filter((a) =>{return a.value == val[1]})[0].label
      }

    },
    loadData(item,callback){
      item.loading = true
      setTimeout(()=>{
        if(item.value == '1'){
          let fow={
            id:1,
            mid:JSON.parse(localStorage.userInfo).id,
          };
          getChosList(fow).then((res) =>{
            if(res.code == 1){
              item.children = res.data.map((a) =>{
                return {
                  value: a.id,
                  label:a.title
                }
              })
              item.loading = false;
              callback()
            }else {
              this.$Message.error(res.msg || '获取圈子失败!');
            }
          })
        }
      },1000)
    },
    // 上传图片
    handleRemove (index) { // 移除图片
      this.uploadList.splice(index, 1)
      this.$forceUpdate()
    },
    //上传失败
    handleSuccessLu(error, file, fileList){
      this.$Notice.warning({
        title: "请上传正确的图片格式",
      });
    },
    handleSuccess (res, file) { // 上传成功回调
      this.uploadList.push(res.result)
      this.$forceUpdate()
    },
    handleBeforeUpload () { // 上传之前钩子函数
      const check = this.uploadList.length < 6;
      if (!check) {
        this.$Notice.warning({
          title: '最多可以上传六张图片'
        });
        return check;
      }
    },
    //上传视频
    handleRemoveVideo (index) { // 移除图片
      this.uploadListVideo.splice(index, 1)
      this.$forceUpdate()
    },
    handleSuccessVideo (res, file) { // 上传成功回调
      this.uploadListVideo.push(res.result)
      this.$forceUpdate()
    },
    //上传失败
    handleSuccessVideoLu(error, file, fileList){
      this.$Notice.warning({
        title: "请上传正确的MP4视频格式",
      });
    },
    handleBeforeUploadVideo () { // 上传之前钩子函数
      const check = this.uploadListVideo.length < 3;
      if (!check) {
        this.$Notice.warning({
          title: '最多可以上传3张图片'
        });
        return check;
      }
    },
    //发布分享
    handleSubmit(name){
      let params = {
        mid:JSON.parse(localStorage.userInfo).id,
        id:this.editRow.id || '',
        title: this.formValidate.titleText,
        content: this.formValidate.contText,
        push_status: this.value1[0] || '',
        circlelist_id: this.value1[1] || '',
        act_id: '',
        thumbs: this.uploadList.join(','),
        video_url: this.uploadListVideo.join(','),
        type: this.uploadListVideo.length > 0 ? 2: 1
      }
      this.$refs[name].validate((valid) => {
        if (valid) {
          editChosInfo(params).then((res) =>{
            if(res.code == '1'){
              this.$Message.success("发布成功")
              this.getList()
            }else {
              this.$Message.error(res.msg || '发布失败!');
            }
          })
        }
      })
    },
  },
};
</script>

<style lang="scss" scoped>
.draftItem {
  .top {
    padding: 10px 20px;
    .top-left {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .left-info{
        display: flex;
        align-items: center;
        .header-img {
          width: 40px;
          height: 40px;
          border-radius: 50%;
        }
        .info {
          margin-left: 5px;
          .name {
            color: #444;
          }
          .time {
            color: #ccc;
            margin-top: 5px;
          }
        }
      }

    }
    .del-box {
      cursor: pointer;
      span{
        padding: 5px 3px;
        margin-right: 3px;

        >i{
          margin-right: 2px;
        }
      }
    }
  }
  .main {
    padding: 0 40px;
    margin-top: 10px;
    .text {
    }
    .imgs {
      .imgs-item {
        width: 30%;
        height: 100px;
        margin: 5px;
      }
    }
  }
}
.live {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .live-left,
  .live-right {
    /*margin-right: 70px;*/
    display: flex;
    align-items: center;
  }
  .live-left {
    .popCla{
      .type-box {
        display:flex;
        align-items:center;
        cursor: pointer;
        .sub-box {
          display:flex;
          align-items:center;
          .demo-upload-list{
            display: inline-block;
            width: 60px;
            height: 60px;
            text-align: center;
            line-height: 60px;
            border: 1px solid transparent;
            border-radius: 4px;
            overflow: hidden;
            background: #fff;
            position: relative;
            box-shadow: 0 1px 1px rgba(0,0,0,.2);
            margin-right: 4px;

          }
          .demo-upload-list img{
            width: 100%;
            height: 100%;
          }
          .demo-upload-list-cover{
            display: none;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0,0,0,.6);
          }
          .demo-upload-list:hover .demo-upload-list-cover{
            display: block;
          }
          .demo-upload-list-cover i{
            color: #fff;
            font-size: 20px;
            cursor: pointer;
            margin: 0 2px;
            z-index: 9999;
          }
        }
      }
    }
    .video {
      /*margin-left: 20px;*/
    }
  }
  .live-right {
    // .drop {
    cursor: pointer;
    .defult {
      display: flex;
      align-items: center;
    }
    .dropMenu {
      .dropItem {
        display: flex;
        align-items: center;
        .icon {
          width: 20px;
        }
        .title {
          flex: 1;
          text-align: center;
        }
      }
    }
    // }
    .sub {
      cursor: pointer;
      color: #fff;
      background-color: #f00;
      border: none;
      width: 80px;
      height: 30px;
      margin-left: 30px;
    }
  }
}
  .leiCla{
    color: #FD5151;
    padding: 5px 3px;
  }
</style>
